/*
 * @Author: yangzonglong
 * @Date: 2021-06-30 14:57:27
 * @version: v1.0.0
 * @Descripttion: 上传控件
 * @LastEditors: 871387321@qq.com 871387321@qq.com
 * @LastEditTime: 2023-11-28 15:31:28
 * @Auditor:
 */
import React, { useCallback, useEffect, useState, useMemo } from 'react';
import { Upload, Button, Form, message } from 'antd';
import { UploadProps as AntdUploadProps } from 'antd/lib/upload/interface';
import { UploadOutlined } from '@ant-design/icons';
import MIME from '@library/components/fileUpload/mime';
import { fileDataSource } from './UploadController';
import { FormItemProps } from '../../components/components/InputFormItemController';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { CanvasItemProps } from './../../interface';
import evalScriptText from './../../eval';
import Icon from './../../../../../.rnext/library/components/icon/Icon';
import moment from 'moment';

const UPLOAD_URL = '/bk/uploadIpfs/workflow?m=dev';
const officeSuffix = ['pdf', 'doc', 'docx', 'xlsx'];
const imgSuffix = ['jpeg', 'gif', 'jpg', 'png', 'bmp', 'ico'];
const DEFAULT_ACCEPT = fileDataSource.join(',');

function handleUrl(url: string | undefined) {
  if (!url || url.includes('http') || url.includes('/bk/getFile/')) {
    return url;
  }

  return '/bk/getFile/' + url;
}
export interface UploadProps extends CanvasItemProps {
  uploadProps?: AntdUploadProps & {
    maxCount?: number;
    showUploadName?: boolean;
    showUploadTime?: boolean;
    maxSize?: string; // 最大上传体积 MB
    uploadUrl?: string;
    downloadUrl?: string;
    downloadScript?: string;
  };
  formItemProps?: FormItemProps;
  disabled?: boolean;
  scriptsChangeData?: object;
  enviromentConfig?: object;
}

export const onHandleViewUrl = (attachPath?: string) => {
  if (!attachPath) return '';
  if (attachPath.startsWith('http')) return window.open(attachPath, '_blank');

  const fileName = attachPath?.split('?')?.[0];
  const suffix = fileName?.split('.').pop()?.toLocaleLowerCase();

  if (suffix) {
    if (imgSuffix.includes(suffix)) {
      const newwindow = window.open(window.location.origin) as any;
      newwindow?.document?.write(`
        <html>
          <title>${window.$app.t('view')}</title>
          <body style="display: flex; justify-content: center; align-items: center">
            <img src=${encodeURI(handleUrl(attachPath)!)} />
          </body>
        </html>
      `);
    } else if (officeSuffix.includes(suffix) && !attachPath.includes('mode=1')) {
      window.open('/bk/previewFile/' + attachPath.replace('/bk/getFile/', ''));
    } else {
      window.open(handleUrl(attachPath));
    }
  }
};

const ComponentUpload = (props: UploadProps) => {
  const { enviromentConfig, disabled, uploadProps, formItemProps, domComplete, scriptsChangeData, initialValue
    , ...canvasProps } = props;

  useQueryControlWrap(canvasProps.id, formItemProps?.name, domComplete);

  const [fileList, setFileList] = useState([]);
  
  const mimeTypes = useMemo(() => {
    const accept = (uploadProps?.accept || DEFAULT_ACCEPT).split(',');
    return accept.map(item => MIME[item]).flat();
  }, [uploadProps?.accept]);

  const beforeUpload = useCallback(
    (file, fileList) => {
      let maxSize: number | string | undefined = uploadProps?.maxSize;

      // 未限制体积未限制数量 允许上传
      if (!maxSize && !uploadProps?.maxCount) {
        return true;
      }

      if (maxSize) {
        maxSize = parseInt(maxSize);
        if (maxSize * 1024 * 1024 < file.size) {
          // 转成k 对比
          message.warning(`不能超过${maxSize} MB`);
          return Upload.LIST_IGNORE;
        }
      }

      if (uploadProps?.maxCount && uploadProps.maxCount === fileList.length - 1) {
        message.warning(`总数量不能超过${uploadProps.maxCount}`);
        return Upload.LIST_IGNORE;
      }

      if (file.type && !mimeTypes.includes(file.type)) {
        message.warning('格式不支持');
        return Upload.LIST_IGNORE;
      }

      return true;
    },
    [uploadProps, mimeTypes]
  );

  const normFile = useCallback((e: any) => {
    if (e.file?.status === 'uploading' && e.file?.percent === 0) {
      window.$app.showLoading();
    }

    if (e.file?.status === 'done') {
      window.$app.hideLoading();
    }

    let list = Array.isArray(e) ? e : e?.fileList || [];
    list.forEach((element: any) => {

      const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo') || '{}');
      element.createdTime = element.createdTime ? element.createdTime : moment().format('YYYY/MM/DD HH:mm:ss');
      element.createdName = element.createdName ? element.createdName : userInfo.name;
      element.linkName = element.linkName ? element.linkName : element.name + (uploadProps?.showUploadName !== false ? ' ' + userInfo.name : '') + (uploadProps?.showUploadTime !== false ? ' ' + moment().format('YYYY/MM/DD HH:mm:ss') : '');

      if (element.response && element.response.filename) {
        element.url = (uploadProps?.downloadUrl || '/bk/getFile/') + element.response.filename;
        if (!element.url.includes('downloadFileName')) {
          if (element.url.includes('?')) {
            element.url = element.url + '&downloadFileName=' + element.response.originalname;
          } else {
            element.url = element.url + '?downloadFileName=' + element.response.originalname;
          }
        }
      }
    });

    setFileList(list);
    return list;

  }, [uploadProps?.downloadUrl, uploadProps?.showUploadName, uploadProps?.showUploadTime]);

  const onPreview = useCallback((file: any) => {
    if (uploadProps?.downloadScript) {
      evalScriptText({
        scriptText: uploadProps.downloadScript,
        extra: {
          _OBJ_: file,
          _ENV_: enviromentConfig || {},
          _OBJ1_: scriptsChangeData
        },
        next: () => { }
      });
    } else {
      window.open(handleUrl(file.url || file.attachPath));
    }
  }, [enviromentConfig, scriptsChangeData, uploadProps]);


  const handleDownload = useCallback((e, file) => {
    e.preventDefault();
    onPreview(file);
  }, [onPreview]);

  const label = localStorage.i18nextLng === 'en' ? formItemProps?.labelEn : formItemProps?.label;

  useEffect(() => {
    if (initialValue
    ) {
      setFileList(initialValue);
    }
  }, [initialValue]);

  const itemRender = useCallback((originNode: any, file: any, fileList: any[], actions: any) => {
    return <div>{
      <div className="ant-upload-list-item ant-upload-list-item-done ant-upload-list-item-list-type-text">
        <div className="ant-upload-list-item-info">
          <span className="ant-upload-span">
            <div className="ant-upload-text-icon">
              <span role="img" aria-label="paper-clip" className="anticon anticon-paper-clip">
                <svg viewBox="64 64 896 896" focusable="false" data-icon="paper-clip" width="1em" height="1em" fill="currentColor" aria-hidden="true">
                  <path d="M779.3 196.6c-94.2-94.2-247.6-94.2-341.7 0l-261 260.8c-1.7 1.7-2.6 4-2.6 6.4s.9 4.7 2.6 6.4l36.9 36.9a9 9 0 0012.7 0l261-260.8c32.4-32.4 75.5-50.2 121.3-50.2s88.9 17.8 121.2 50.2c32.4 32.4 50.2 75.5 50.2 121.2 0 45.8-17.8 88.8-50.2 121.2l-266 265.9-43.1 43.1c-40.3 40.3-105.8 40.3-146.1 0-19.5-19.5-30.2-45.4-30.2-73s10.7-53.5 30.2-73l263.9-263.8c6.7-6.6 15.5-10.3 24.9-10.3h.1c9.4 0 18.1 3.7 24.7 10.3 6.7 6.7 10.3 15.5 10.3 24.9 0 9.3-3.7 18.1-10.3 24.7L372.4 653c-1.7 1.7-2.6 4-2.6 6.4s.9 4.7 2.6 6.4l36.9 36.9a9 9 0 0012.7 0l215.6-215.6c19.9-19.9 30.8-46.3 30.8-74.4s-11-54.6-30.8-74.4c-41.1-41.1-107.9-41-149 0L463 364 224.8 602.1A172.22 172.22 0 00174 724.8c0 46.3 18.1 89.8 50.8 122.5 33.9 33.8 78.3 50.7 122.7 50.7 44.4 0 88.8-16.9 122.6-50.7l309.2-309C824.8 492.7 850 432 850 367.5c.1-64.6-25.1-125.3-70.7-170.9z"></path>
                </svg>
              </span>
            </div>
            <a href="javascript:;" rel="noopener noreferrer" className="ant-upload-list-item-name" title={file.linkName || file.name} onClick={e => onHandleViewUrl(file.url || file.attachPath)}>{file.linkName || file.name}</a>

            {/* <Icon
              className="ant-upload-list-item-card-actions"
              icon="&#xe62c;"
              onClick={() => {
                // window.open(handleUrl(ele.attachPath || ele.response?.filename || ele.url));
              }}
            /> */}

            {(file.url || file.attachPath) && (
              <span className="ant-upload-list-item-card-actions">
                <button onClick={e => handleDownload(e, file)} title="下载文件" type="button" className="ant-btn ant-btn-text ant-btn-sm ant-btn-icon-only ant-upload-list-item-card-actions-btn">
                  <Icon
                    icon="&#xe62c;"
                  />
                </button>
              </span>
            )}

            {!disabled ? <span className="ant-upload-list-item-card-actions">
              <button onClick={() => actions.remove()} title="删除文件" type="button" className="ant-btn ant-btn-text ant-btn-sm ant-btn-icon-only ant-upload-list-item-card-actions-btn">
                <Icon
                  icon="&#xe66d;"
                />
              </button>
            </span> : null}
          </span>
        </div>
      </div>
    }</div>;
  }, [disabled, handleDownload]);

  return (
    <Form.Item
      {...canvasProps}
      {...props.formItemProps}
      valuePropName="fileList"
      getValueFromEvent={normFile}
      label={label}
    >
      <Upload
        {...uploadProps}
        onPreview={onPreview}
        fileList={fileList}
        action={uploadProps?.uploadUrl || UPLOAD_URL}
        beforeUpload={beforeUpload}
        itemRender={itemRender}
        disabled={disabled}
      >
        <Button icon={<UploadOutlined />} disabled={disabled}>
          {window.$app.t('upload')}
        </Button>
      </Upload>
    </Form.Item>
  );
};

export default ComponentUpload;
